package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.OSSObject;
import com.ruoyi.file.config.AliOssConfig;
import org.apache.commons.codec.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Primary
@Service
public class AliOssSysFileServiceImpl implements ISysFileService {

    @Autowired
    private OSS ossClient;

    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;

    /**
     * 上传文件
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        ossClient.putObject(AliOssConfig.BUCKET_NAME, fileName, inputStream);

        //文件访问路径
        return endpoint.split("//")[0] + "//" + AliOssConfig.BUCKET_NAME + "." + endpoint.split("//")[1] + "/" + fileName;
    }
}
